package main

import (
	"context"
	"fmt"
	"net"
	"time"

	"golang/protobuf/src/model"
	"golang/protobuf/src/rpc"

	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

var (
	port = "19123"
)

type Service struct {
}

func (this *Service) Forward(ctx context.Context, request *model.Request) (*model.Response, error) {
	fmt.Println("S:Recv:", request)
	response := &model.Response{
		Str: "Hi, " + request.Str + "!",
	}
	fmt.Println("S:Send:", response)
	return response, nil
}

func S() {
	s := grpc.NewServer()
	rpc.RegisterStreamServer(s, &Service{})
	reflection.Register(s)

	l, err := net.Listen("tcp", ":"+port)
	if err != nil {
		panic(err)
	}

	s.Serve(l)
}

func C() {
	conn, err := grpc.Dial("127.0.0.1:"+port, grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	request := &model.Request{Str: "Gricks"}

	fmt.Println("C:Send:", request)
	c := rpc.NewStreamClient(conn)
	response, err := c.Forward(context.Background(), request)
	if err != nil {
		panic(err)
	}
	fmt.Println("C:Recv:", response)
}

func main() {
	go S()
	time.Sleep(time.Second)
	for i := 0; i < 3; i++ {
		C()
		time.Sleep(time.Second)
	}
}
